package model

import (
	"context"
	"fmt"

	"github.com/Masterminds/squirrel"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ ProfileModel = (*customProfileModel)(nil)

type (
	// ProfileModel is an interface to be customized, add more methods here,
	// and implement the added methods in customProfileModel.
	ProfileModel interface {
		profileModel
		RowBuilder() squirrel.SelectBuilder
		Truncate(ctx context.Context)
	}

	customProfileModel struct {
		*defaultProfileModel
	}
)

// NewProfileModel returns a model for the database table.
func NewProfileModel(conn sqlx.SqlConn, c cache.CacheConf) ProfileModel {
	return &customProfileModel{
		defaultProfileModel: newProfileModel(conn, c),
	}
}

func (m *defaultProfileModel) RowBuilder() squirrel.SelectBuilder {
	return squirrel.Select(profileRows).From(m.table)
}

func (m defaultProfileModel) Truncate(ctx context.Context) {
	build := m.RowBuilder()
	query, values, err := build.ToSql()
	if err == nil {
		var resp []*Profile
		err = m.QueryRowsNoCacheCtx(ctx, &resp, query, values...)
		if err == nil {
			for _, r := range resp {
				m.Delete(ctx, r.Id)
			}
			m.ExecNoCacheCtx(ctx, fmt.Sprintf("TRUNCATE %s ", m.tableName()))
		}
	}
}
